IF OBJECT_ID('ssf.ddl_exists_table_or_view') IS NOT NULL
	DROP PROCEDURE ssf.ddl_exists_table_or_view
GO

CREATE PROCEDURE ssf.ddl_exists_table_or_view
	@object_name NVARCHAR(512)
	, @exists_fl BIT = NULL OUTPUT
	, @is_table_fl BIT = NULL OUTPUT
AS
/*

*/

SET NOCOUNT ON

-- ============
/*<code_comment><![CDATA[declare dynamic sql variables]]></code_comment>*/
DECLARE	@sql_error INT
			, @row_count BIGINT
			, @sql VARCHAR(MAX)
			, @nsql NVARCHAR(MAX)
			, @crlf CHAR(2) = CHAR(13) + CHAR(10)
			, @quote CHAR(1) = CHAR(39)
			, @two_quotes CHAR(2) = CHAR(39) + CHAR(39)
			, @tab CHAR(1) = CHAR(9)
-- ============

-- ============
/*<code_comment><![CDATA[initialize variables]]></code_comment>*/
SELECT	@exists_fl = NULL
			, @is_table_fl = NULL
-- ============

-- ============
/*<code_comment><![CDATA[test table existence]]></code_comment>*/
EXECUTE @sql_error = ssf.ddl_exists_table
	@table_name = @object_name
	-- NVARCHAR(512)
	, @exists_fl = @exists_fl OUTPUT
	-- BIT

IF ISNULL(@sql_error, 1) <> 0
OR @exists_fl IS NULL
BEGIN
	RAISERROR('Failed to test the table existence.', 16, 1)
	RETURN @sql_error
END
-- ============

-- ============
/*<code_comment><![CDATA[if the object is a table, ]]></code_comment>*/
IF @exists_fl = 1
	SET @is_table_fl = 1
-- ============
ELSE
-- ============
/*<code_comment><![CDATA[otherwise, test view existence]]></code_comment>*/
BEGIN
	EXECUTE @sql_error = ssf.ddl_exists_view
		@view_name = @object_name
		-- NVARCHAR(512)
		, @exists_fl = @exists_fl OUTPUT
		-- BIT

	IF ISNULL(@sql_error, 1) <> 0
	OR @exists_fl IS NULL
	BEGIN
		RAISERROR('Failed to test the view existence.', 16, 1)
		RETURN @sql_error
	END
	
	IF @exists_fl = 1
		SET @is_table_fl = 0
END
-- ============

RETURN @@ERROR
GO
